Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
postcss-value-parser
Advanced tools
The postcss-value-parser package is a tool to parse and manipulate values from CSS declarations. It can be used to analyze, transform, and understand the structure of CSS property values, making it easier to work with complex CSS strings in JavaScript.
Parsing CSS values
This feature allows you to parse a CSS value into an abstract syntax tree (AST), which can then be traversed or manipulated. The code sample demonstrates parsing a CSS rgba color value.
const valueParser = require('postcss-value-parser');
const parsed = valueParser('rgba(34, 12, 64, 0.3)');
console.log(parsed.nodes);
Walking through parsed values
This feature allows you to walk through the nodes of the parsed value and perform operations on each node. The code sample demonstrates walking through a parsed CSS declaration to find and log pixel values.
const valueParser = require('postcss-value-parser');
const parsed = valueParser('10px solid black');
valueParser.walk(parsed.nodes, (node) => {
if (node.type === 'word' && /px$/.test(node.value)) {
console.log(`Found pixel value: ${node.value}`);
}
});
Stringifying parsed values
After manipulating the parsed AST, you can convert it back to a string. The code sample demonstrates modifying a scale function's Y value and then stringifying the modified AST back into a CSS value.
const valueParser = require('postcss-value-parser');
const parsed = valueParser('scale(1, 1.2)');
parsed.nodes[1].value = 1.5;
const stringified = valueParser.stringify(parsed);
console.log(stringified);
css-value-parser is a package that offers similar functionality to postcss-value-parser. It can parse CSS property values into JavaScript objects. However, it may not have as rich an API for manipulation or walking through the parsed values as postcss-value-parser.
css-tree is a more comprehensive CSS parser that can parse entire stylesheets and includes the ability to parse individual values. It differs from postcss-value-parser in that it is designed to handle full CSS parsing and AST manipulation, not just values.
Transforms CSS declaration values and at-rule parameters into a tree of nodes, and provides a simple traversal API.
var valueParser = require('postcss-value-parser');
var cssBackgroundValue = 'url(foo.png) no-repeat 40px 73%';
var parsedValue = valueParser(cssBackgroundValue);
// parsedValue exposes an API described below,
// e.g. parsedValue.walk(..), parsedValue.toString(), etc.
For example, parsing the value rgba(233, 45, 66, .5)
will return the following:
{
nodes: [
{
type: 'function',
value: 'rgba',
before: '',
after: '',
nodes: [
{ type: 'word', value: '233' },
{ type: 'div', value: ',', before: '', after: ' ' },
{ type: 'word', value: '45' },
{ type: 'div', value: ',', before: '', after: ' ' },
{ type: 'word', value: '66' },
{ type: 'div', value: ',', before: ' ', after: '' },
{ type: 'word', value: '.5' }
]
}
]
}
If you wanted to convert each rgba()
value in sourceCSS
to a hex value, you could do so like this:
var valueParser = require('postcss-value-parser');
var parsed = valueParser(sourceCSS);
// walk() will visit all the of the nodes in the tree,
// invoking the callback for each.
parsed.walk(function (node) {
// Since we only want to transform rgba() values,
// we can ignore anything else.
if (node.type !== 'function' && node.value !== 'rgba') return;
// We can make an array of the rgba() arguments to feed to a
// convertToHex() function
var color = node.nodes.filter(function (node) {
return node.type === 'word';
}).map(function (node) {
return Number(node.value);
}); // [233, 45, 66, .5]
// Now we will transform the existing rgba() function node
// into a word node with the hex value
node.type = 'word';
node.value = convertToHex(color);
})
parsed.toString(); // #E92D42
Each node is an object with these common properties:
word
, string
, div
, space
, comment
, or function
).
Each type is documented below.value
property; but what exactly value
means
is specific to the node type. Details are documented for each type below.10px 20px
, the word
node
whose value is 20px
will have a sourceIndex
of 5
.The catch-all node type that includes keywords (e.g. no-repeat
),
quantities (e.g. 20px
, 75%
, 1.5
), and hex colors (e.g. #e6e6e6
).
Node-specific properties:
A quoted string value, e.g. "something"
in content: "something";
.
Node-specific properties:
"
or '
.true
if the string was not closed properly. e.g. "unclosed string
.A divider, for example
,
in animation-duration: 1s, 2s, 3s
/
in border-radius: 10px / 23px
:
in (min-width: 700px)
Node-specific properties:
,
, /
, or :
(see examples above).Whitespace used as a separator, e.g.
occurring twice in border: 1px solid black;
.
Node-specific properties:
A CSS comment starts with /*
and ends with */
Node-specific properties:
/*
and */
true
if the comment was not closed properly. e.g. /* comment without an end
.A CSS function, e.g. rgb(0,0,0)
or url(foo.bar)
.
Function nodes have nodes nested within them: the function arguments.
Additional properties:
rgb
in rgb(0,0,0)
.
in rgb( 0,0,0)
.
in rgb(0,0,0 )
.true
if the parentheses was not closed properly. e.g. ( unclosed-function
.Media features surrounded by parentheses are considered functions with an
empty value. For example, (min-width: 700px)
parses to these nodes:
[
{
type: 'function', value: '', before: '', after: '',
nodes: [
{ type: 'word', value: 'min-width' },
{ type: 'div', value: ':', before: '', after: ' ' },
{ type: 'word', value: '700px' }
]
}
]
url()
functions can be parsed a little bit differently depending on
whether the first character in the argument is a quotation mark.
url( /gfx/img/bg.jpg )
parses to:
{ type: 'function', sourceIndex: 0, value: 'url', before: ' ', after: ' ', nodes: [
{ type: 'word', sourceIndex: 5, value: '/gfx/img/bg.jpg' }
] }
url( "/gfx/img/bg.jpg" )
, on the other hand, parses to:
{ type: 'function', sourceIndex: 0, value: 'url', before: ' ', after: ' ', nodes: [
type: 'string', sourceIndex: 5, quote: '"', value: '/gfx/img/bg.jpg' },
] }
The unicode-range CSS descriptor sets the specific range of characters to be
used from a font defined by @font-face and made available
for use on the current page (unicode-range: U+0025-00FF
).
Node-specific properties:
var valueParser = require('postcss-value-parser');
Parses quantity
, distinguishing the number from the unit. Returns an object like the following:
// Given 2rem
{
number: '2',
unit: 'rem'
}
If the quantity
argument cannot be parsed as a number, returns false
.
This function does not parse complete values: you cannot pass it 1px solid black
and expect px
as
the unit. Instead, you should pass it single quantities only. Parse 1px solid black
, then pass it
the stringified 1px
node (a word
node) to parse the number and unit.
Stringifies a node or array of nodes.
The custom
function is called for each node
; return a string to override the default behaviour.
Walks each provided node, recursively walking all descendent nodes within functions.
Returning false
in the callback
will prevent traversal of descendent nodes (within functions).
You can use this feature to for shallow iteration, walking over only the immediate children.
Note: This only applies if bubble
is false
(which is the default).
By default, the tree is walked from the outermost node inwards.
To reverse the direction, pass true
for the bubble
argument.
The callback
is invoked with three arguments: callback(node, index, nodes)
.
node
: The current node.index
: The index of the current node.nodes
: The complete nodes array passed to walk()
.Returns the valueParser
instance.
Returns the parsed node tree.
The array of nodes.
Stringifies the node tree.
Walks each node inside parsed.nodes
. See the documentation for valueParser.walk()
above.
MIT © Bogdan Chadkin
FAQs
Transforms css values and at-rule params into the tree
The npm package postcss-value-parser receives a total of 29,796,456 weekly downloads. As such, postcss-value-parser popularity was classified as popular.
We found that postcss-value-parser demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.